package com.ljx.offer;

/**
 * @author 李捷禧
 * Date: 2023/4/2
 * ClassName: C_36
 */

public class C_36 {
    //设置一个res是一个游标指针
    //head是一个头指针
    Node res,head;

    /**
     * 使用中序遍历
     * @param root
     * @return
     */
    public Node treeToDoublyList(Node root) {
        if(root == null) return null;
        dfs(root);
        head.left = res;
        res.right = head;
        return head;
    }

    void dfs(Node root){
        if(root == null) return;
        dfs(root.left);
        //把第一个值给head
        if(res != null) res.right = root;
        else head = root;
        root.left = res;
        res = root;
        dfs(root.right);
    }


    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }
}
